//
//  DiaryChatView.swift
//  imprint
//
//  Created by 小柠檬🍋 on 2025/2/7.
//

import SwiftUI
import Kingfisher

//首页日记评论的
struct DiaryCommentView: View {
    @EnvironmentObject var themeManager: ThemeManager
    @Binding var diaryBean: DiaryBean
    @Binding var commentStatus: Int //一旦变化，整个试图就更新。
    @StateObject var viewModel : DiaryItemViewModel
    @State var iconCenterLeading : CGFloat = 0
    @State var iconCenterTrailing : CGFloat = 0
    @State var iconCenterTop : CGFloat = 0
    @State var iconCenterBottom : CGFloat = 0
    @State var textColor : String? = nil

    var body: some View {
        VStack(alignment: .leading, spacing: 0) {
            ForEach(Array((diaryBean.temOther ?? []).enumerated()), id: \.element.id) { index, item in
                if diaryBean.isMultiple() {
                    DiaryCommentItemView(item: item, diaryBean: $diaryBean, textColor: $textColor, viewModel: viewModel)
                        .padding(.leading, item.bot ? 0 : 24)
                        .padding(.top,4)
                } else {
                    DiaryCommentItemView(item: item, diaryBean: $diaryBean, textColor: $textColor, viewModel: viewModel)
                        .padding(.leading, index == 0 ? 0 : 24)
                        .padding(.top,4)
                }
            }
            //有更多按钮
            if diaryBean.showMoreComment() {
                Text("展开更多评论")
                    .font(.system(size: 12))
                    .foregroundStyle(.bgDel)
                    .padding(.leading, diaryBean.isMultiple() ? 8 : 48)
                    .padding(.top, 5)
            }
        }
        .padding(.leading, viewModel.bubble?.leading ?? 8)
        .padding(.trailing, viewModel.bubble?.trailing ?? 8)
        .padding(.top, viewModel.bubble?.top ?? 8)
        .padding(.bottom, viewModel.bubble?.bottom ?? 10)
        .frame(maxWidth: .infinity,alignment: .leading)
        .padding(.leading , iconCenterLeading)
        .padding(.trailing, iconCenterTrailing)
        .padding(.top , iconCenterTop)
        .padding(.bottom , iconCenterBottom)
        .background(
            ZStack {
                if let bubble = viewModel.bubble {
                    BubbleBgView(bubble: bubble)
                        .padding(.top, 5)
                } else {
                    Color.bgItem.opacityBg(0.1)
                        .cornerRadius(17)
                }
            }.id(UUID().uuidString)

        )
        //整体试图的间距，如果有气泡则为0，因为气泡有自带间距等等
        .padding(.leading ,viewModel.bubble != nil ? 0 : 12)
        .padding(.top ,viewModel.bubble != nil ? 0 : 12)
        .onAppear{
            if !viewModel.isInit{
                viewModel.getBubble(bean: diaryBean)
                viewModel.isInit = true
            }
        }.onReceive(viewModel.$bubble) {  newValue in
            iconCenterLeading = newValue?.iconCenter?.leading ?? 0
            iconCenterTrailing = newValue?.iconCenter?.trailing ?? 0
            iconCenterTop = newValue?.iconCenter?.top ?? 0
            iconCenterBottom = newValue?.iconCenter?.bottom ?? 0
            textColor = newValue?.textColor
        }
    }
}

//首页评论item
struct DiaryCommentItemView: View {
    @EnvironmentObject var themeManager: ThemeManager
    @State private var showDelAiDialog = false //删除回应
    @State private var showHistoryComment = false //历史评论
    var item: DiaryTemComment
    @Binding var diaryBean: DiaryBean
    @Binding var textColor : String?
    @StateObject var viewModel : DiaryItemViewModel
    
    var body: some View {
        VStack(alignment: .leading,spacing: 0) {
            HStack(spacing: 0) {
                KFImage(URL(string: item.avatar.formatCdn()))
                    .resizable()
                    .placeholder{
                        Image(.appDefaultLogo)
                            .resizable()
                            .scaledToFill()
                            .padding(EdgeInsets(top: 5, leading: 5, bottom: 5, trailing: 5))
                            .frame(width: 24,height: 24)
                            .clipShape(Circle())
                    }
                    .background(Color.hex("515151").opacity(0.1))
                    .scaledToFill()
                    .frame(width: 24,height: 24)
                    .clipShape(Circle())
                Text(item.name ?? "")
                    .font(.system(size: 13))
                    .foregroundStyle(textColor != nil ? (Color.hex(textColor ?? "")) : (item.isBot() ? themeManager.themeColor : .bgNormalText4))
                    .padding(.leading, 4)
            }
            Text(item.content ?? "")
                .font(.system(size: 13))
                .foregroundStyle(textColor != nil ? (Color.hex(textColor  ?? "")) : (item.isBot() ? themeManager.themeColor : .bgNormalText2))
                .padding(.leading, 24)
                .fixedSize(horizontal: false, vertical: true) // 允许垂直扩展，不设置的话，不知道为啥有时候自动截断
        }.frame(maxWidth: .infinity, alignment: .leading)
            .contentShape(Rectangle())
            .onTapGesture {
                NotificationCenter.default.post(name: .showComment, object: (diaryBean,item.aiRoleId))
            }
            .contextMenu {
                Button("查看评论") {
                    NotificationCenter.default.post(name: .showComment, object: (diaryBean,item.aiRoleId))
                }
                Button("重新回应") {
                    ActiveAiExt.doAiReply(diaryBean, item.aiRoleId ?? "")
                }
                Button("删除回应", role: .destructive) {
                    showDelAiDialog.toggle()
                }
                Button("历史回应") {
                    showHistoryComment.toggle()
                }
                Button("装扮气泡") {
                    pathManager.jump(type: JumpType.BUBBLE_DIARY,data: viewModel.bean)
                }
            }
            .alert("温馨提示",isPresented:$showDelAiDialog) {
                Button("取消",role: .cancel){}
                Button("确定删除",role: .destructive) {
                    viewModel.delAIReply(diaryBean: $diaryBean, aiRoleId : item.aiRoleId ?? "")
                }
            } message: {
                Text("是否确定删除该回应")
            }
            .sheet(isPresented: $showHistoryComment) {
                HistoryCommentDialogView(bean: $diaryBean,aiRoleId: item.aiRoleId ?? "") {
                    showHistoryComment = false
                }.presentationDetents([.fraction(0.9), .large])
                
            }
    }
}

//#Preview {
//    DiaryCommentView(item1: DiaryTemComment("","我是名字","我是内容我是内容我是内容我我是内容我是内容我是内容我我是内容我是内容我是内容我我是内容我是内容我是内容我"),temOther: [DiaryTemComment("","我是名字","我是内容"), DiaryTemComment("","我是名字","我是内容")])
//}


//定义预览提供者
struct DiaryComment_Previews: PreviewProvider {
    static var previews: some View {
        @State var showComment = false
        @State var bean : DiaryBean = DiaryBean(content: "日记内容")
        @State var commentStatus : Int = 1 //刷新评论使用
        @StateObject var viewModel = DiaryItemViewModel(bean: bean)
        
        //使用预览共享配置
        configurePreviewEnvironment(for:   DiaryCommentView(diaryBean: $bean,commentStatus : $commentStatus, viewModel: viewModel))
    }
}
